package com.tbynet.jwp.admin.tag;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.tbynet.jwp.admin.AdminController;
import com.tbynet.jwp.model.TermTaxonomy;
import com.tbynet.jwp.model.Terms;
import com.tbynet.jwp.service.TermService;
import com.tbynet.jwp.service.TermTaxonomyService;

public class TagAdminController extends AdminController {

	@Inject
	TermService termService;
	
	@Inject
	TermTaxonomyService taxonomyService;
	
	public void index() {
		set("parents", termService.getParents(TermTaxonomy.TAXONOMY_POST_TAG));
		
		render("index.html");
	}
	
	public void search() {
		String q = getPara("q");
		
		Page<Terms> page = termService.search(getPage(), getSize(), TermTaxonomy.TAXONOMY_POST_TAG, q);
		
		ok(Ret.by("data", page));
	}
	
	public void edit() {
		set("term", termService.getTerm(getPara("term_id"), TermTaxonomy.TAXONOMY_POST_TAG));
		set("parents", termService.getParents(TermTaxonomy.TAXONOMY_POST_TAG));
		
		render("edit.html");
	}
	
	public void save() {
		String name = getPara("name");
		String slug = getPara("slug");
		String description = getPara("description");
		
		Terms term = new Terms();
		term.setName(name);
		term.setSlug(slug);
		term.setTermGroup(0l);
		
		TermTaxonomy taxonomy = new TermTaxonomy();
		taxonomy.setTaxonomy(TermTaxonomy.TAXONOMY_POST_TAG);
		taxonomy.setDescription(description);
		taxonomy.setCount(0l);
		
		if(termService.save(term, taxonomy)) {
			ok(Ret.by("msg", "添加标签成功.").set("data", term.getTermId()));
		} else {
			fail("添加标签失败，请联系管理员.");
		}
	}
	
	public void update() {
		String termId = getPara("term_id");
		String name = getPara("name");
		String slug = getPara("slug");
		String description = getPara("description");
		
		Terms term = termService.getTerm(termId);
		term.setName(name);
		term.setSlug(slug);
		
		TermTaxonomy taxonomy = taxonomyService.getTermTaxonomy(term.getTermId(), TermTaxonomy.TAXONOMY_POST_TAG);
		taxonomy.setDescription(description);
		
		if(termService.update(term, taxonomy)) {
			ok(Ret.by("msg", "更新标签成功.").set("data", term.getTermId()));
		} else {
			fail("更新标签失败，请联系管理员.");
		}
	}
	
	public void delete() {
		
	}
}
